import request from '@/utils/request'

// 使用@RequestParam的表单提交，兼容多种token返回结构
export const registerService = async ({ username, phone, password }) => {
  const form = new URLSearchParams()
  form.append('username', username || '')
  form.append('phone', phone || '')
  form.append('password', password || '')

  console.log('[registerService] Request Payload:', {
    username,
    phone,
    password: '******'
  })

  const res = await request.post('/auth/register', form, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })

  console.log('[registerService] Raw Response:', res)

  let token =
    res?.token ??
    res?.data?.token ??
    res?.data?.data?.token ??
    res?.data ??
    res

  if (token != null && typeof token !== 'string') {
    try { token = String(token) } catch { token = undefined }
  }

  console.log('[registerService] Parsed token:', token, 'typeof:', typeof token)

  return { raw: res, token }
}
